package com.mzba.easy.weibo.widget;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.CommentEntry;
import com.mzba.easy.weibo.db.CommentGson;
import com.mzba.easy.weibo.db.EmotionField;
import com.mzba.easy.weibo.db.StatusTimelineEntry;
import com.mzba.easy.weibo.ui.CommentsActivity;
import com.mzba.easy.weibo.ui.GridViewAdapter;
import com.mzba.easy.weibo.ui.NewsActivity;
import com.mzba.easy.weibo.ui.PhotoDetailActivity;
import com.mzba.easy.weibo.ui.UserinfoActivity;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.DateUtil;
import com.mzba.easy.weibo.util.ImageLoader;
import com.mzba.easy.weibo.util.ServiceUtils;
import com.mzba.easy.weibo.util.StringUtil;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
/**
 * 
 * @author 06peng
 *
 */
public class StatusTimeLineView extends LinearLayout implements BasicUIEvent, Callback {
	
	private Context context;
	private View statusTimelineItem;
	private View commentItem;
//	private View commentBody;
	private LinearLayout preView;
	private StatusTimelineEntry entry;
	private ImageLoader photoLoader;
	private LayoutParams params;
	private LayoutParams paramsTop;
	private Handler handler;
	private List<CommentEntry> commentEntries;
	public CustomDialog dialog;
	private WeiboManager weibo;
	private boolean isRetweet = false;
//	private boolean isShowCommentBody = false;
	
	public static final int DESTROYDIALOG = 0x00000101;
	private static final int comment_status = 0x00000102;
	private static final int comment_status_error = 0x00000103;
	private static final int reply_comment = 0x00000104;
	
	ImageButton emotionView;
	ImageView retweetView;
	LinearLayout retweetSelectLayout;
	Button commentView;
	EditText editView;
	LinearLayout bodyLayout;
	
	RemoteImageView avatarView;
	CustomTextView textView;
	TextView replyView;
	
	private PopupWindow pop;
	
	public StatusTimeLineView(Context context, StatusTimelineEntry entry) {
		super(context);
		this.context = context;
		handler = new Handler(this);
		weibo = new WeiboManager(context);
		this.entry = entry;
		photoLoader = new ImageLoader(context, AppContext.FRIENDSTIMELINE_PATH);
		try {
			initWidget();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.setOrientation(LinearLayout.VERTICAL);
		this.addView(statusTimelineItem);
		params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.leftMargin = 35;
		paramsTop = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		paramsTop.topMargin = 15;
		
		View view = LayoutInflater.from(context).inflate(R.layout.emotion_gridview, null);
		GridView gridView = (GridView) view.findViewById(R.id.emotion_gridview);
		GridViewAdapter gridAdapter = new GridViewAdapter(context);
		gridView.setAdapter(gridAdapter);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		pop.update();
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				try {
					pop.dismiss();
					EmotionField filed = AppContext.getInstance().getEmotionFields().get(arg2);
					editView.append(filed.getPhrase());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	
	public StatusTimeLineView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public StatusTimeLineView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	private void initWidget() throws Exception {
		ViewHolder holder = null;
		if (statusTimelineItem == null) {
			statusTimelineItem = LayoutInflater.from(context).inflate(R.layout.status_timeline_item, null);
			holder = new ViewHolder();
			holder.avatarView = (RemoteImageView) statusTimelineItem.findViewById(R.id.iv_author_photo);
			holder.textView = (CustomTextView) statusTimelineItem.findViewById(R.id.status_timeline_text);
			holder.timeView = (TextView) statusTimelineItem.findViewById(R.id.status_timeline_time);
			holder.photoLayout = (RelativeLayout) statusTimelineItem.findViewById(R.id.status_timeline_photo_layout);
			holder.photoView = (ImageView) statusTimelineItem.findViewById(R.id.status_timeline_photo);
			holder.sourceView = (TextView) statusTimelineItem.findViewById(R.id.status_timeline_from);
			holder.retweetView = (TextView) statusTimelineItem.findViewById(R.id.status_timeline_retweet);
			holder.commentView = (TextView) statusTimelineItem.findViewById(R.id.status_timeline_comment);
			holder.retweetLayout = (LinearLayout) statusTimelineItem.findViewById(R.id.status_timeline_retweet_layout);
			holder.retweetTextView = (CustomTextView) statusTimelineItem.findViewById(R.id.status_timeline_retweet_text);
			holder.retweetTimeView = (TextView) statusTimelineItem.findViewById(R.id.status_timeline_retweet_time);
			holder.retweetPhotoLayout = (RelativeLayout) statusTimelineItem.findViewById(R.id.status_timeline_retweet_photo_layout);
			holder.retweetPhotoView = (ImageView) statusTimelineItem.findViewById(R.id.status_timeline_retweet_photo);
			holder.retweetSourceView = (TextView) statusTimelineItem.findViewById(R.id.status_timeline_retweet_from);
			holder.retweetRetweetView = (TextView) statusTimelineItem.findViewById(R.id.status_timeline_retweet_retweet);
			holder.retweetCommentView = (TextView) statusTimelineItem.findViewById(R.id.status_timeline_retweet_comment);
			statusTimelineItem.setTag(holder);
		} else {
			holder = (ViewHolder) statusTimelineItem.getTag();
		}
		holder.avatarView.setDefaultImage(R.drawable.avatar_default_big);
		if (entry.getUser() != null && entry.getUser().getProfile_image_url() != null) {
			holder.avatarView.setImageUrl(entry.getUser().getProfile_image_url());
		}
		holder.avatarView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, UserinfoActivity.class);
				intent.putExtra("userid", entry.getUser().getId());
				context.startActivity(intent);
			}
		});
		String username = entry.getUser().getScreen_name() + ":" + "&nbsp;";
		holder.textView.setText(entry.getText(), username, AppContext.getInstance().getFaceMap());
		holder.timeView.setText(DateUtil.getCreateAt(entry.getCreated_at()));
		if (StringUtil.isNotBlank(entry.getThumbnail_pic())) {
			holder.photoLayout.setVisibility(View.VISIBLE);
			photoLoader.DisplayImage(entry.getThumbnail_pic(), holder.photoView, R.drawable.avatar_default_big);
		} else {
			holder.photoLayout.setVisibility(View.GONE);
		}
		holder.sourceView.setText(Html.fromHtml("来自" + entry.getSource()));
		if (entry.getReposts_count() > 0) {
			holder.retweetView.setText("转发(" + entry.getReposts_count() + ")");
		} else {
			holder.retweetView.setText("转发");
		}
		if (entry.getComments_count() > 0) {
			holder.commentView.setText("评论(" + entry.getComments_count() + ")");
		} else {
			holder.commentView.setText("评论");
		}
		
		holder.commentView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (preView == null) {
					createCommentItemView();
					StatusTimeLineView.this.addView(commentItem, params);
					commentItem.setVisibility(View.VISIBLE);
//					isShowCommentBody = true;
				} else {
					if (preView == StatusTimeLineView.this) {
						if (commentItem.isShown()) {
							StatusTimeLineView.this.removeView(commentItem);
							commentItem.setVisibility(View.GONE);
//							isShowCommentBody = false;
						} else {
							StatusTimeLineView.this.addView(commentItem, params);
							commentItem.setVisibility(View.VISIBLE);
//							isShowCommentBody = true;
						}
					} else {
						preView.removeView(commentItem);
						commentItem.setVisibility(View.GONE);
						StatusTimeLineView.this.addView(commentItem, params);
						commentItem.setVisibility(View.VISIBLE);
//						isShowCommentBody = true;
					}
				}
				preView = StatusTimeLineView.this;
//				if (isShowCommentBody) {
//					if (entry.getComments_count() > 0) {
//						loading();
//						UICore.eventTask(StatusTimeLineView.this, (BasicActivity) context, AppContext.get_Comment_By_Statusid, null, entry.getId());
//					}
//				}
			}
		});
		
		holder.retweetView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, NewsActivity.class);
				intent.putExtra(AppContext.NEWTYPE, 2);
				intent.putExtra("id", entry.getId());
				context.startActivity(intent);
			}
		});
		
		holder.photoView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				byte[] tempBytes = null;
				try {
					String filename = ServiceUtils.convertUrlToFileName(entry.getThumbnail_pic());
					tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
							android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.FRIENDSTIMELINE_PATH + "/" + filename)));
				} catch (Exception e) {
					e.printStackTrace();
				}
				Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class);
				bigPicIntent.putExtra("pic_big", entry.getOriginal_pic());
				bigPicIntent.putExtra("thumbnail", tempBytes);
				context.startActivity(bigPicIntent);
				
			}
		});
		
		if (entry.getRetweeted_status() != null) {
			holder.retweetLayout.setVisibility(View.VISIBLE);
			String username2 = entry.getRetweeted_status().getUser().getScreen_name() + ":" + "&nbsp;";
			holder.retweetTextView.setText(entry.getRetweeted_status().getText(), username2, AppContext.getInstance().getFaceMap());
			holder.retweetTimeView.setText(DateUtil.getCreateAt(entry.getRetweeted_status().getCreated_at()));
			if (StringUtil.isNotBlank(entry.getRetweeted_status().getThumbnail_pic())) {
				holder.retweetPhotoLayout.setVisibility(View.VISIBLE);
				photoLoader.DisplayImage(entry.getRetweeted_status().getThumbnail_pic(), holder.retweetPhotoView, R.drawable.avatar_default_big);
			} else {
				holder.retweetPhotoLayout.setVisibility(View.GONE);
			}
			holder.retweetSourceView.setText(Html.fromHtml("来自" + entry.getRetweeted_status().getSource()));
			if (entry.getRetweeted_status().getReposts_count() > 0) {
				holder.retweetRetweetView.setText("转发(" + entry.getRetweeted_status().getReposts_count() + ")");
			} else {
				holder.retweetRetweetView.setText("转发");
			}
			if (entry.getRetweeted_status().getComments_count() > 0) {
				holder.retweetCommentView.setText("评论(" + entry.getRetweeted_status().getComments_count() + ")");
			} else {
				holder.retweetCommentView.setText("评论");
			}
			holder.retweetCommentView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (entry.getRetweeted_status().getComments_count() > 0) {
						Intent intent = new Intent(context, CommentsActivity.class);
						intent.putExtra("id", entry.getRetweeted_status().getId());
						context.startActivity(intent);
					} else {
						Intent intent = new Intent(context, CommentsActivity.class);
						intent.putExtra("id", entry.getRetweeted_status().getId());
						context.startActivity(intent);
					}
				}
			});
			holder.retweetRetweetView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, NewsActivity.class);
					intent.putExtra(AppContext.NEWTYPE, 2);
					intent.putExtra("id", entry.getId());
					intent.putExtra("reid", entry.getRetweeted_status().getId());
					context.startActivity(intent);
				}
			});
			
			holder.retweetPhotoView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					byte[] tempBytes = null;
					try {
						String filename = ServiceUtils.convertUrlToFileName(entry.getRetweeted_status().getThumbnail_pic());
						tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
								android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.FRIENDSTIMELINE_PATH + "/" + filename)));
					} catch (Exception e) {
						e.printStackTrace();
					}
					Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class);
					bigPicIntent.putExtra("pic_big", entry.getRetweeted_status().getOriginal_pic());
					bigPicIntent.putExtra("thumbnail", tempBytes);
					context.startActivity(bigPicIntent);
				}
			});
		} else {
			holder.retweetLayout.setVisibility(View.GONE);
		}
	}
	
	private void createCommentItemView() {
		try {
			commentItem = LayoutInflater.from(context).inflate(R.layout.timeline_comment_item, null);
			editView = (EditText) commentItem.findViewById(R.id.timeline_comment_edit);
			emotionView = (ImageButton) commentItem.findViewById(R.id.timeline_comment_emotion);
			retweetView = (ImageView) commentItem.findViewById(R.id.timeline_comment_retweet_select);
			retweetSelectLayout = (LinearLayout) commentItem.findViewById(R.id.timeline_comment_retweet_select_layout);
			commentView = (Button) commentItem.findViewById(R.id.timeline_comment_comment);
			bodyLayout = (LinearLayout) commentItem.findViewById(R.id.timeline_comment_body_layout);
			
			TextView moreCommentView = new TextView(context);
			moreCommentView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, CommentsActivity.class);
					intent.putExtra("id", entry.getId());
					context.startActivity(intent);
				}
			});
			
			ImageView imageLine = new ImageView(context);
			imageLine.setBackgroundResource(R.drawable.divider_horizontal_timeline);
			bodyLayout.addView(imageLine, paramsTop);
			
			LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lp.gravity = Gravity.CENTER_HORIZONTAL;
			lp.topMargin = 10;
			lp.bottomMargin = 10;
			moreCommentView.setText(">>查看评论列表<<");
			bodyLayout.addView(moreCommentView, lp);
			
			avatarView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, UserinfoActivity.class);
					intent.putExtra("userid", entry.getUser().getId());
					context.startActivity(intent);
				}
			});
			
			commentView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					loading();
					String content = editView.getText().toString().trim();
					CommentEntry commentEntry = (CommentEntry) editView.getTag();
					if (commentEntry != null) {
						Object[] objs = new Object[4];
						objs[0] = content;
						objs[1] = entry.getId();
						objs[2] = commentEntry.getId();
						objs[3] = isRetweet == true ? 1 : 0;
						UICore.eventTask(StatusTimeLineView.this, (BasicActivity) context, reply_comment, "", objs); 
					} else {
						Object[] objs = new Object[3];
						objs[0] = content;
						objs[1] = entry.getId();
						objs[2] = isRetweet == true ? 1 : 0;
						UICore.eventTask(StatusTimeLineView.this, (BasicActivity) context, comment_status, "", objs);
					}
				}
			});
			
			retweetSelectLayout.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (isRetweet) {
						isRetweet = false;
						retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_unselect);
					} else {
						isRetweet = true;
						retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_select);
					}
				}
			});
			emotionView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (!pop.isShowing()) {
						pop.showAtLocation(commentItem, Gravity.BOTTOM, 0, 0);
					} else {
						pop.dismiss();
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
//	private void createCommentBodyView(final CommentEntry entry) {
//		try {
//			commentBody = LayoutInflater.from(context).inflate(R.layout.comment_body_item, null);
//			avatarView = (RemoteImageView) commentBody.findViewById(R.id.iv_author_photo);
//			replyView = (TextView) commentBody.findViewById(R.id.comment_body_reply);
//			textView = (CustomTextView) commentBody.findViewById(R.id.comment_body_text);
//			commentBody.setTag(entry);
//			avatarView.setDefaultImage(R.drawable.avatar_default_big);
//			avatarView.setImageUrl(entry.getUser().getProfile_image_url());
//			String username = entry.getUser().getScreen_name() + ":" + "&nbsp;";
//			textView.setText(entry.getText(), username, AppContext.getInstance().getFaceMap());
//			bodyLayout.addView(commentBody, paramsTop);
//			ImageView imageLine = new ImageView(context);
//			imageLine.setBackgroundResource(R.drawable.divider_horizontal_timeline);
//			bodyLayout.addView(imageLine, paramsTop);
//			
//			replyView.setOnClickListener(new View.OnClickListener() {
//				
//				@Override
//				public void onClick(View v) {
//					editView.setText("回复@" + entry.getUser().getScreen_name() + ":");
//					editView.setTag(entry);
//					editView.setFocusable(true);
//					editView.setFocusableInTouchMode(true);
//				}
//			});
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	public static class ViewHolder {
		RemoteImageView avatarView;
		CustomTextView textView;
		TextView timeView;
		RelativeLayout photoLayout;
		ImageView photoView;
		TextView sourceView;
		TextView retweetView;
		TextView commentView;
		
		LinearLayout retweetLayout;
		CustomTextView retweetTextView;
		TextView retweetTimeView;
		RelativeLayout retweetPhotoLayout;
		ImageView retweetPhotoView;
		TextView retweetSourceView;
		TextView retweetRetweetView;
		TextView retweetCommentView;
	}
	
	public List<CommentEntry> getCommentEntries() {
		return commentEntries;
	}
	
	public LinearLayout getBodyLayout() {
		return bodyLayout;
	}

	@Override
	public void execute(int mes, Object obj) {
		try {
			switch (mes) {
			case AppContext.get_Comment_By_Statusid:
				String statusId = obj.toString();
				CommentGson gson = weibo.getCommentsByStatusid(11, 1, statusId);
				if (gson != null) {
					commentEntries = gson.getComments();
					handler.sendEmptyMessage(AppContext.get_Comment_By_Statusid);
				} else {
					destroyDialog();
				}
				break;
			case comment_status:
				Object[] objs = (Object[]) obj;
				CommentEntry commentEntry = weibo.commentStatus(objs[0].toString(), objs[1].toString(), Integer.parseInt(objs[2].toString()));
				if (commentEntry != null) {
					addComment(commentEntry);
				} else {
					handler.sendEmptyMessage(comment_status_error);
				}
				break;
			case reply_comment:
				Object[] objs2 = (Object[]) obj;
				CommentEntry commentEntry2 = weibo.replayCommemnt(objs2[0].toString(), objs2[1].toString(), objs2[2].toString(),
						Integer.parseInt(objs2[3].toString()));
				if (commentEntry2 != null) {
					addComment(commentEntry2);
				} else {
					handler.sendEmptyMessage(comment_status_error);
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void loading() {
		try {
			if (dialog == null || !dialog.isShowing()) {
				View progressview = LayoutInflater.from(context).inflate(R.layout.progress_dialog, null);
				CustomDialog.Builder progressBuilder = new CustomDialog.Builder(context);
				progressBuilder.setContentView(progressview);
				dialog = progressBuilder.create();
				dialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void destroyDialog() {
		handler.sendEmptyMessage(DESTROYDIALOG);
	}
	
	public void onToast(String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case AppContext.get_Comment_By_Statusid:
//			try {
//				bodyLayout.removeAllViews();
//				if (commentEntries != null) {
//					for (int i = 0;i < commentEntries.size();i++) {
//						CommentEntry entry = commentEntries.get(i);
//						createCommentBodyView(entry);
//					}
//					if (commentEntries.size() > 10) {
//						TextView moreCommentView = new TextView(context);
//						moreCommentView.setOnClickListener(new View.OnClickListener() {
//							
//							@Override
//							public void onClick(View v) {
//								Intent intent = new Intent(context, CommentsActivity.class);
//								intent.putExtra("id", entry.getId());
//								context.startActivity(intent);
//							}
//						});
//						LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//						lp.gravity = Gravity.CENTER_HORIZONTAL;
//						lp.topMargin = 10;
//						lp.bottomMargin = 10;
//						moreCommentView.setText(">>查看更多评论<<");
//						bodyLayout.addView(moreCommentView, lp);
//					}
//				}
//				if (editView != null) {
//					editView.setText("");
//				}
//				destroyDialog();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			break;
		case DESTROYDIALOG:
			if (dialog != null && dialog.isShowing()) {
				dialog.cancel();
			}
			break;
		case comment_status_error:
			destroyDialog();
			onToast("评论失败!");
			break;
		default:
			break;
		}
		return false;
	}
	
	private void addComment(CommentEntry commentEntry) {
		try {
			List<CommentEntry> temp = new ArrayList<CommentEntry>();
			temp.add(commentEntry);
			if (commentEntries != null) {
				for (int i = 0; i < commentEntries.size();i++) {
					temp.add(commentEntries.get(i));
				}
			}
			handler.sendEmptyMessage(AppContext.get_Comment_By_Statusid);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
